Go 自动打开系统默认浏览器 | 您所在的位置:网站首页 › 浏览器open xdg-open › Go 自动打开系统默认浏览器 |
因为 Go 可以编译 Windows Darwin Linux 三个平台的二进制文件,如果编写一个 Web 项目,启动后可以自动打开浏览器,那就非常方便了。
首先看下三个平台打开浏览器的命令 Darwin 1$ open http://baidu.comWindows 1$ start http://baidu.comLinux 1$ xdg-open http://baidu.com接下来需要 Go 能区分平台,这里需要 runtime 包。 123import "runtime"platform := runtime.GOOS// darwin windows linux好接下来就可以写代码了 12345678910111213141516171819202122232425262728package main// 打开系统默认浏览器import ( "fmt" "os/exec" "runtime")var commands = map[string]string{ "windows": "start", "darwin": "open", "linux": "xdg-open",}func Open(uri string) error { run, ok := commands[runtime.GOOS] if !ok { return fmt.Errorf("don't know how to open things on %s platform", runtime.GOOS) } cmd := exec.Command(run, uri) return cmd.Start()}func main() { Open("http://baidu.com")} 最近更新 Alfred Workflow 命令行帮助工具 最近热读 Go 判断数组中是否包含某个 item Vim 高级功能 vimgrep 全局搜索文件 办理北京工作居住证的一些细节 Go 语法错误:Non-declaration statement outside function body Mac 电脑查看字体文件位置 扫码关注公众号,或搜索公众号“温欣爸比” 及时获取我的最新文章 赏谢谢你请我喝咖啡 支付宝 微信 |
CopyRight 2018-2019 实验室设备网 版权所有 |